<?php
//if not a real page (nobody called us here, just user trying to hack
if ((!isset($_SESSION['realpage']))
 || ($_SESSION['realpage'] == false))
 {
 	require './hack.php';
 	die(" ");
 }

 
error_reporting(E_ALL);

require_once "./class.InfoSingleton.php";
require_once "./class.BaseDBUtils.php";
require_once "./class.user.php";
require_once "./class.Group.php";
require_once "./class.Talkback.php";
require_once "./class.Message.php";

if (0 > version_compare(PHP_VERSION, '5')) {
	die('This file was generated for PHP 5');
}


class DBConnection extends BaseDBUtils
{
	
 	private function __clone() {}
 
 	public function getError()
 	{
 		return $this->error;
 	}
 	
 	/** 
 	 * REGION_START user management
 	 */
 	public function login($username,$password)
 	{
 		$user_name = $this->paramHandler($username);
 		$user_pass = $this->salt($user_name,$this->paramHandler($password));
 		$rez = $this->qry("SELECT * FROM users u WHERE u.handle ='$user_name' AND u.password ='$user_pass' LIMIT 1;" ,2);

 		if ($rez == null)
 		{
 			return null;
 		}
 		return User::factorUser($rez);
 	}
 
	public function getUserswall($uid)
	{
		if (!is_numeric($uid)) 
		{
		   	return 0;
		}
		$rez = $this->qry("SELECT * FROM groups WHERE friendsgroup=$uid LIMIT 1;" ,2);
		
		return $rez['gid'];  
	}
	
	public function getUser($uid)
 	{
 		if (!is_numeric($uid))
 			return  null;
 		
 		$rez = $this->qry("SELECT * FROM users u WHERE u.uid =$uid LIMIT 1;" ,2);

 		if ($rez == null)
 		{
 			return null;
 		}
 		
 		return User::factorUser($rez);
 	}
	
	public function isHandleAvailable($handle)
	{
		$user_name = $this->paramHandler($handle);
		//check if handle is available
		$rez = $this->qry("SELECT * FROM users u WHERE u.handle ='$user_name' LIMIT 1;" ,2);
		if (sizeof($rez) > 1)
			return false;
		return true;
	}
	
 	public function register($username,$password,$firstname,$lastname,$birthday,$about,$email)
	{
		if (!$this->isHandleAvailable($username))
		{
			return null;
		}
		if (!$this->isValidEmail($email))
		{
			return null;
		}
		
 		$user_name = $this->paramHandler($username);
 		$user_pass = $this->salt($user_name,$this->paramHandler($password));
 		$fname = $this->paramHandler($firstname);
 		$lname = $this->paramHandler($lastname);
 		$abt = $this->ParamHandler($this->retainLines($about));
 		$birthday = $this->calcdate($birthday);
		
 		$gdesc = $fname.' '.$lname.'&lsquo;s friends';
 		// insert user
 		$sql="INSERT INTO users (handle,password,first_name,sur_name,birthday,last_updated,email,about)
			VALUES
				('$user_name','$user_pass','$fname','$lname','$birthday',now(),'$email','$abt');";
 		
 		if (!$this->execute($sql))
 			return false;
 		
 		// get UID
 		$sql="SELECT max(uid) FROM users WHERE handle='$user_name'";
 		$uid = $this->qry($sql,1);
 		$uid = $uid[0]; // get selected val
		
 		// create group
 		if (!$this->createGroup($fname.' '.$lname, $gdesc, 1, $uid, $uid))
 		{
 			return false;
 		}
 			
 		return $this->login($username,$password);
 	}
 	
 	public function UpdateUserDetails($fname, $lname, $email, $bday, $about, $uid)
 	{
 		if(!is_numeric($uid))
 		{
 			return false;
 		}
 		if (!$this->isValidEmail($email))
		{
			return false;
		}
		
 		$fname = $this->paramHandler($fname);
 		$lname = $this->paramHandler($lname);
 		$about = $this->paramHandler($this->retainLines($about));
 		$bday = $this->calcdate($bday);
 		$gname = $fname.' '.$lname;
 		$gdesc = $gname.'&lsquo;s friends';
 		$sql = "update users set first_name = '$fname', sur_name = '$lname', birthday = '$bday', email = '$email', about = '$about' where uid = $uid;";
 		$rez = $this->execute($sql);
 		if($rez != true)
 		{
 			return false;
 		}
 		
 		$sql = "update groups set name = '$gname',description='$gdesc' where friendsgroup = $uid";
 		
 		$rez = $this->execute($sql);
 		if($rez == true)
 		{
 			return true;
 		}
 		return false;
 	}
 	
	/** 
 	 * REGION_END user management
 	 */
 	
 	//arg
 	
 	/** 
 	 * REGION_START group management
     */
 	
 	
	public function getGroupUsers($gid)  
	{
		if (!is_numeric($gid)) 
		{
		   	return array();
		}
		
		$sql = "SELECT u.uid,u.handle,u.first_name,u.sur_name,u.birthday,u.email,u.last_updated,u.about
				FROM users u,relation_type rt
				WHERE u.uid = rt.uid AND rt.gid = $gid AND (rt.type = 'M' OR rt.type = 'O')
				ORDER BY u.first_name,u.first_name";
		
		$rez = $this->qry($sql ,4);
		
   		$tmpCont = array();
   		
   		$ind = 0;
   		$row = mysql_fetch_assoc($rez);
   		
   		while(null != $row)
   		{
   			$tmpCont[$ind]= User::factorUser($row);
   			$ind++;
   			$row = mysql_fetch_assoc($rez);
   		}
   		
   		return $tmpCont;
		
	} // end of function get group users
	 
	public function getGroupWBUsers($gid)
	{
		if (!is_numeric($gid))
		{
			return array();
		}
	
		$sql = "SELECT u.uid,u.handle,u.first_name,u.sur_name,u.birthday,u.email,u.last_updated,u.about
					FROM users u,relation_type rt
					WHERE u.uid = rt.uid AND rt.gid = $gid AND (rt.type = 'P')
					ORDER BY u.first_name,u.first_name";
	
		$rez = $this->qry($sql ,4);
	
		$tmpCont = array();
		 
		$ind = 0;
		$row = mysql_fetch_assoc($rez);
		 
		while(null != $row)
		{
			$tmpCont[$ind]= User::factorUser($row);
			$ind++;
			$row = mysql_fetch_assoc($rez);
		}
		 
		return $tmpCont;
	
	} // end of function get group users
	
	public function isGroupAvailable($handle)
	{
		$name = $this->paramHandler($handle);
		//check if handle is available
		$rez = $this->qry("SELECT * FROM groups g WHERE g.name ='$name' LIMIT 1;" ,2);
		if (sizeof($rez) > 1)
			return false;
		return true;
	}
	
 	public function createGroup($gname,$gdesc,$visibility,$friendsgroup,$ownerUid)
 	{

 		if(!is_numeric($ownerUid))
 		{
 		 	return false;
 		}
 		
 		$gdesc = $this->paramHandler($this->retainLines($gdesc));
 		$gname = $this->paramHandler($gname);
 		
 		// properly set visibility
 		if ($visibility == 1 || 'true' == $visibility)
 		{
 			$visibility = '1';
 		}
 		else
 		{
 			$visibility = '0';
 		}
 		
 		if (!is_numeric ($friendsgroup))
 		{
 			$friendsgroup = 0;
 		}
	
 	 		
 		// get a temporary group name, change later
 		$tmpGname=$this->genRandomString() . $gname;
 		while (!$this->isGroupAvailable($tmpGname))
 		{
 			$tmpGname=$this->genRandomString() . $gname;
 		}
 		
 		// create group
 		$sql="INSERT INTO groups (name,description,visibility,last_updated,friendsgroup)
			VALUES
								('$tmpGname','$gdesc',$visibility,now(),$ownerUid);";
 		$tmp=$this->execute($sql);
 		if (!$tmp)
 		{
 			return false;
 		}
 			
 		$sql = "SELECT max(gid) FROM groups WHERE name ='$tmpGname'";
 		
 		$gid = $this->qry($sql,1);
 		$gid = $gid[0]; // get selected val
 		
 		// return to required group name
 		$sql = "UPDATE groups 
 				SET name='$gname',
 					friendsgroup=$friendsgroup 
 				WHERE name ='$tmpGname' AND friendsgroup='$ownerUid' ;";
 		
 		$tmp=$this->execute($sql,1); // tmp is only here for debug.
 		
 		if($this->addRelation($gid, $ownerUid, 'O'))
 		{
 			return $gid;
 		}	
 		else
 		{
 			return false;
 		}	
 	}
 	
 	public function getRandomGroups($uid,$maxGroups)
    {  
   		if (!is_numeric($uid))
   		{
   			return array(); // fail
   		}
   		if (!is_numeric($maxGroups)) 
   		{
   			return array();
   		}
   		
   		// select all the groups, with which we have a relation (gid is in relation)
   
   		$sql="(SELECT g.gid as 'gid', g.name as 'name', rt.type as 'relation', visibility as 'visibility', description as 'description', 0 as 'friendsgroup'
				 FROM groups g, relation_type rt
				 WHERE g.gid=rt.gid
				  AND NOT rt.type = 'L'
				  AND rt.uid=$uid
				  AND g.friendsgroup=0
				)
				  union
				(
				 SELECT gid as 'gid', name as 'name', 'N' as 'relation', visibility as 'visibility', description as 'description',0 as 'friendsgroup'
				 FROM groups
				 WHERE gid not in (SELECT g.gid
				                    FROM groups g, relation_type rt
				                    WHERE g.gid=rt.gid
				                    AND NOT rt.type = 'L'
				                    AND rt.uid=$uid
				                    AND g.friendsgroup=0
				                  )
				    AND visibility=1
				    AND friendsgroup=0
				)LIMIT $maxGroups
   		";
   		
   		$rez= $this->qry($sql,4);
   		$tmpCont = array();
   		$ind = 0;
   		$row = mysql_fetch_assoc($rez);
  		while($row != null)
   		{
   			$tmpCont[$ind]= Group::factorGroup($row);
   			$ind++;
   			$row = mysql_fetch_assoc($rez);
   		}
   		
   		return $tmpCont;
   }	//end of function random groups
   
	public function searchGroup($user,$criteria,$limit)  
	{
		if (!is_numeric($user)) 
		{
		   	return array();
		}
		if (!is_numeric($limit)) 
		{
		   	$limit = 15;
		}
		
		$criteria= $this->paramHandler($criteria) . '%';
		//select user's groups
		//add all visible groups without the intersection with previous group
		$sql=" (SELECT g.gid as 'gid', g.name as 'name', rt.type as 'relation', g.visibility as 'visibility', g.description as 'description',0 as 'friendsgroup'
				 FROM groups g, relation_type rt
				 WHERE g.gid=rt.gid
				  AND rt.type <> 'L'
				  AND rt.uid=$user
				  AND g.name like '$criteria'
				  AND g.friendsgroup=0
				)
				  union
				(
				  SELECT gid as 'gid', name as 'name', 'N' as 'relation', visibility as 'visibility', description as 'description',0 as 'friendsgroup'
				 FROM groups
				 WHERE gid not in (SELECT g.gid
				                    FROM groups g, relation_type rt
				                    WHERE g.gid=rt.gid
				                    AND rt.type <> 'L'
				                    AND rt.uid=$user
				                    AND g.name like '$criteria'
				                    AND g.friendsgroup=0
				                  )
				    AND visibility=1
				    AND name like '$criteria'
				    AND friendsgroup=0
				)
				limit $limit;
		";
   		
   		$rez= $this->qry($sql,4);
   		$tmpCont = array();
   		
   		$ind = 0;
   		$row = mysql_fetch_assoc($rez);
   		while(null != $row)
   		{
   			$tmpCont[$ind]= Group::factorGroup($row);
   			$ind++;
   			$row = mysql_fetch_assoc($rez);
   		}
   		
   		return $tmpCont;
		
	} // end of function search group
	
	public function getUserGroups($user,$limit,$downpour)  
	{
		if (!is_numeric($user)) 
		{
		   	return array();
		}
		if (!is_numeric($limit)) 
		{
		   	$limit = 15;
		}
		if (!is_numeric($downpour)) 
		{
		   	$limit = 0;
		}
		
		
		//select user's groups
		//add all visible groups without the intersection with previous group
		$sql="SELECT g.gid as 'gid', g.name as 'name', rt.type as 'relation', g.visibility as 'visibility', g.description as 'description',0 as 'friendsgroup'
				 FROM groups g, relation_type rt
				 WHERE g.gid=rt.gid
				  AND rt.uid=$user
				  AND g.gid > $downpour
				  AND g.friendsgroup=0
				  AND rt.type <> 'D'
				  AND rt.type <> 'P'
				  AND rt.type <> 'L'
				  ORDER BY g.gid
				limit $limit;
		";
   		
   		$rez= $this->qry($sql,4);
   		$tmpCont = array();
   		
   		$ind = 0;
   		$row = mysql_fetch_assoc($rez);
   		while(null != $row)
   		{
   			$tmpCont[$ind]= Group::factorGroup($row);
   			$ind++;
   			$row = mysql_fetch_assoc($rez);
   		}
   		
   		return $tmpCont;
		
	} // end of function get groups
	
	public function getGroupPosts($group,$limit,$downpour,$minvisibility)  
	{
		if (!is_numeric($group)) 
		{
		   	return array();
		}
		if (!is_numeric($limit)) 
		{
		   	$limit = 15;
		}
		if (!isset($downpour) || !is_numeric($downpour)) 
		{
		   	$limit = 0;
		}
		
		
		//select user's groups
		//add all visible groups without the intersection with previous group
		$sql="SELECT p.uid as 'uid', u.first_name as 'fname', u.sur_name as 'lname', p.pid as 'pid', p.topic as 'topic', p.content as 'content', p.Created as 'timestamp', p.visibility as 'visibility'
				FROM posts p,users u
				WHERE p.gid = $group
				      AND p.visibility >= $minvisibility
				      AND u.uid = p.uid
				      AND p.pid > $downpour
				ORDER BY p.pid
				LIMIT 5;
		";
   		
   		$rez= $this->qry($sql,4);
   		$tmpCont = array();
   		
   		$ind = 0;
   		$row = mysql_fetch_assoc($rez);
   		while(null != $row)
   		{
   			$tmpCont[$ind]= Post::factorPost($row);
   			$ind++;
   			$row = mysql_fetch_assoc($rez);
   		}
   		
   		return $tmpCont;
		
	} // end of function get groups' posets
	
	
	
	public function setTalkbackVisibility($uid,$tbid,$vis)
	{
		
		if ((!is_numeric($uid)) || (!is_numeric($tbid))|| (!is_numeric($vis))) 
		{
		   return false;
		}
		$sql="SELECT rt.type as 'type'
				FROM relation_type rt, posts p, talkbacks tb
				WHERE p.gid = rt.gid AND p.pid = tb.pid 
  				AND tb.id=$tbid AND rt.uid=$uid;
		";
   		
   		$rez= $this->qry($sql,2);
   		$rez= $rez['type'];
   		
   		if ($rez != 'O')
   		{
   			return false; // no privilage
   		}
   		
   		// set visibility
   		$sql="update talkbacks set visibility=$vis where id=$tbid ;";
   		$rez= $this->execute($sql);
   		
   		if (!$rez) return false;
 		return true;
	} // end setTalkbackVisibility
	
	public function setPostVisibility($uid,$pid,$vis)
	{
		
		if ((!is_numeric($uid)) || (!is_numeric($pid))|| (!is_numeric($vis))) 
		{
		   return false;
		}
		$sql="SELECT rt.type as 'type'
				FROM relation_type rt, posts p
				WHERE p.gid = rt.gid 
  				AND p.pid=$pid AND rt.uid=$uid;
		";
   		
   		$rez= $this->qry($sql,2);
   		$rez= $rez['type'];
   		
   		if ($rez != 'O')
   		{
   			return false; // no privilage
   		}
   		
   		// set visibility
   		$sql="update posts set visibility=$vis where pid=$pid ;";
   		$rez= $this->execute($sql);
   		
   		if (!$rez) return false;
 		return true;
	} // end setTalkbackVisibility
	
	public function getPostTalkbacks($pid,$limit,$downpour,$minvisibility)  
	{
	
		if (!is_numeric($pid)) 
		{
		   	return array();
		}
		if (!is_numeric($limit)) 
		{
		   	$limit = 15;
		}
		if (!isset($downpour) || !is_numeric($downpour)) 
		{
		   	$limit = 0;
		}
		
		
		//select user's groups
		//add all visible groups without the intersection with previous group
		$sql="SELECT u.first_name as 'fname',u.sur_name as 'lname',u.uid as 'uid',tb.id as 'tbid',tb.Created as 'publishtime',tb.content as 'content',tb.visibility as 'visibility'
				FROM
				  users u, talkbacks tb
				WHERE
				  u.uid = tb.uid
				  AND tb.pid = $pid  
 				  AND tb.id > $downpour
				  AND tb.visibility >=$minvisibility
				ORDER BY tb.Created
				limit $limit
		";
   		
   		$rez= $this->qry($sql,4);
   		$tmpCont = array();
   		
   		$ind = 0;
   		$row = mysql_fetch_assoc($rez);
   		while(null != $row)
   		{
   			$tmpCont[$ind]= Talkback::factorTalkback($row);
   			$ind++;
   			$row = mysql_fetch_assoc($rez);
   		}
   		
   		return $tmpCont;
		
	} // end of function get post's talkbacks

	public function publishPost($user,$gid,$content,$topic)
	{
						
		if (!is_numeric($user) || !is_numeric($gid)) 
		{
		   	return false;
		}
		
		$rel=$this->getRelationType($gid, $user);
		
		if(($rel != 'M') && ($rel != 'O')  )
		{
			return false;
		}
		$topic=$this->paramHandler($topic);
		$content=$this->paramHandler($this->retainLines($content));
		
 		$sql="INSERT INTO  posts ( uid,gid,topic,content,last_updated,Created,visibility )
			VALUES
		    ($user,$gid,'$topic','$content',now(),now(),1);";
 		$tmp = $this->execute($sql);
 		if (!$tmp)
 			return false;
 		return true;
	}
	
	public function publishTalkback($user,$pid,$content)
	{
						
		if (!is_numeric($user) || !is_numeric($pid)) 
		{
		   	return false;
		}
		
		//validate relation to group
		$sql="SELECT rt.type as 'type'
				FROM posts p, relation_type rt
				WHERE p.pid = $pid AND rt.gid = p.gid AND rt.uid = $user ;";
		
		$rel=$this->qry($sql,2);		
		$rel=$rel['type'];
		
		if(($rel != 'M') && ($rel != 'O')  || (!isset($rel)))
		{
			return false;
		}
		
		$content=$this->paramHandler($this->retainLines($content));
		 
		// insert to db
 		$sql=" INSERT INTO talkbacks ( uid,pid,visibility,content,last_updated,Created ) 
			VALUES
		    ($user,$pid,1,'$content',now(),now());";
 		
 		$tmp = $this->execute($sql);
 		if (!$tmp)
 			return false;
 		return true;
		
	}
		
	public function getGroup($user,$gid)  
	{
						
		if (!is_numeric($user) || !is_numeric($gid)) 
		{
		   	return array();
		}
		
		$sql = "SELECT * FROM groups WHERE gid=$gid;";
   		$rez= $this->qry($sql,2);
   		$grp = Group::factorGroup($rez);
   		
		$sql = "SELECT rt.type as 'type' FROM relation_type rt WHERE rt.uid=$user AND rt.gid=$gid LIMIT 1;";
		
   		$rez= $this->qry($sql,2);
   		
   		$reltn=$rez['type'];
   		
   		//if (($reltn != 'M') && ($reltn !='O)) return null;
   		
 		switch ($reltn)
 		{
 			case 'D': //denied
 				if ($grp->Visible == 0)
 				{
 					return null;
 				}
 				//return null;
 				//break;
 			case 'P':
 				//return null;
 				//break;
 			case 'L':
 				
 			case null:
 				if ($grp->Visible == 0)
 				{
 					return null;
 				}
 				if ($reltn == 'P')
 					$grp->relation = 'P';
 				else
 					$grp->relation = 'N';
				return $grp;
 				break;
 			default:
 				break;
 		}
 		
 		$grp->relation = $reltn;
 		
		return $grp;
	} // end of function get group
	
	/** 
 	 * REGION_END group management
 	 */
 	
 	//arg
 	
 	/** 
 	 * REGION_START relation management
 	 */
	
 	/*/ add a new relation between a group and a user.
 	// types
 	//  O= owner
 	//  M= member
    //  p= pending owner authorization
    //  D= denied
    //  I= invited by owner
    //  N= none
 	// this function is protected(!), no validity checks!*/
 	public  function addRelation($gid,$uid,$type)
 	{
 		if ((!is_numeric($gid)) || (!is_numeric($uid)) || (strlen($type) > 1)) return false;
 		
 		$tmp = $this->getRelationType($gid, $uid);
 		
 		if ($tmp == $type) return  true;
 		
 		if ( $tmp == 'N' )
 		{
 			
	 		// insert connection between user and 
	 		$sql="INSERT INTO relation_type (uid,gid,type,last_updated)
				VALUES
			    ($uid,$gid,'$type',now());";
	 		$tmp = $this->execute($sql);
	 		if (!$tmp)
	 			return false;
	 		return true;
 		}
 		
 		if ($tmp != 'O')
 			return  $this->updateRelation($gid, $uid, $type);
 			
 		return false; // user is owner, cannot resign!
 	}
 	
	protected function updateRelation($gid,$uid,$type)
 	{
 		// insert connection between user and 
 		$sql="UPDATE relation_type SET type='$type', last_updated=now() WHERE uid=$uid AND gid=$gid ;";
 		$tmp = $this->execute($sql);
 		
 		if (!$tmp) return false;
 		return true;
 	}
 	
	public function getRelationType($gid,$uid)
 	{

 		// insert connection between user and 
 		$sql="SELECT * FROM relation_type WHERE uid=$uid AND gid=$gid";
 		$tmp = $this->qry($sql,2);
 		
 		if ((null == $tmp) ||(sizeof($tmp) < 1)) return 'N';
 		
 		return $tmp['type'];
 	}
    
 
 	/** 
 	 * REGION_END relation management
 	 */
 	
 	/** 
 	 * REGION_START user connections
 	 */
 	public function getUserMessages($uid,$limit,$downpour)
 	{
 		$tmp  = array();
 		
 		if (!is_numeric($uid) || !is_numeric($limit) || !is_numeric($downpour)) return $tmp;
 		
 		
 		if(!isset($downpour ) || $downpour == '' || $downpour == '0' ||$downpour == 0)
 			$limiter = '';
 		else 
 		{
 			//$nlimit = $this->calcdate($downpour);
 			$limiter = ' AND mid < '.$downpour .' ';
 		}
 		
 		
 		// query
	 	$sql="SELECT m.mid AS 'thread', m.sender as 'sender',m.receiver as 'receiver',m.Created as 'date',m.content as 'message',u1.first_name as 'senderName',u2.first_name as 'receiverName'
			  FROM messages m,users u1,users u2
			  WHERE  ( m.sender=$uid OR m.receiver=$uid )
			  	  ".$limiter."
				  AND m.Created >= (SELECT max(m2.Created) 
			     			        FROM messages m2
			                    	WHERE  (m.sender = m2.sender   AND m.receiver = m2.receiver) OR
			                    		   (m.sender = m2.receiver AND m.receiver = m2.sender))
			      AND u1.uid=m.sender AND u2.uid=m.receiver
			  ORDER BY m.Created DESC 
			  LIMIT $limit";
	 	$rez= $this->qry($sql,4);
   		
	 	// create
   		$ind = 0;
   		$row = mysql_fetch_assoc($rez);
   		while(null != $row)
   		{
   			$tmp[$ind]= Message::factorMessage($row);
   			$ind++;
   			$row = mysql_fetch_assoc($rez);
   		}
   		
   		return $tmp;	 	
 	}
 	
	public function getThread($uid,$friend,$limit,$downpour)
 	{
 		$tmp  = array();
 		
 		if (!is_numeric($uid) || !is_numeric($friend) || !is_numeric($downpour)) return $tmp;
 		
 		// handle downpour as nlimit, limiter is of downpour	
 		if(!isset($downpour ) || $downpour == '' || $downpour == '0' ||$downpour == 0)
 			$limiter = '';
 		else 
 		{
 			$limiter = " AND mid < $downpour ";
 		}
 		// query
	 	$sql = "SELECT mid AS 'thread',sender,receiver,Created as 'date',content as 'message',u1.first_name as 'senderName', u2.first_name as 'receiverName'
				FROM messages m,users u1, users u2
				WHERE ((m.sender=$uid AND m.receiver=$friend) OR (m.sender=$friend AND m.receiver=$uid))".$limiter."  
						AND u1.uid=m.sender AND u2.uid=m.receiver         
				ORDER BY Created DESC
				LIMIT $limit";
	 	
	 	$rez= $this->qry($sql,4);
   		
	 	// create
   		$ind = 0;
   		$row = mysql_fetch_assoc($rez);
   		while(null != $row)
   		{
   			$tmp[$ind]= Message::factorMessage($row);
   			$ind++;
   			$row = mysql_fetch_assoc($rez);
   		}
   		
   		return $tmp;	 	
 	}
 	
	public function sendMessage($uid,$friend,$content)
 	{
 		
 		if (!is_numeric($uid) || !is_numeric($friend)) return false;
 		$content = $this->paramHandler($this->retainLines($content));
 		
 		// query
	 	$sql = "INSERT INTO messages (sender,receiver,content,Created)
				VALUES ($uid,$friend,'$content',now())";
	 	
	 		
	 	if (!$this->execute($sql))
 			return false;
 		return true;
 	}
 	
 	 	
 	public function getRandomFriends($uid,$maxFriends)
    {  
   		if (!is_numeric($uid))
   		{
   			return array(); // fail
   		}
   		if (!is_numeric($maxFriends)) 
   		{
   			return array();
   		}
   		//get gid
   		$sql = "SELECT gid
   				FROM groups
   				WHERE friendsgroup=$uid";
   		$rez= $this->qry($sql,2);
   		
   		$gid=$rez['gid'];
   		
   		//get friends' groups
   		$sql = "SELECT g.gid as 'gid', g.name as 'name', rt.type as 'relation', g.visibility as 'visibility', g.description as 'description', g.friendsgroup as 'friendsgroup'
				FROM groups g,relation_type rt
				WHERE g.friendsgroup=rt.uid
				 	  AND rt.type = 'M'
				 	  AND rt.gid=$gid
				ORDER BY  RAND() 
				LIMIT $maxFriends
   		";
   		
   		$rez= $this->qry($sql,4);
   		$tmpCont = array();
   		$ind = 0;
   		$row = mysql_fetch_assoc($rez);
  		while($row != null)
   		{
   			$tmpCont[$ind]= Group::factorGroup($row);
   			$ind++;
   			$row = mysql_fetch_assoc($rez);
   		}
   		
   		return $tmpCont;
   }	//end of function random friends
   
	public function searchFriend($user,$criteria,$limit)  
	{
		if (!is_numeric($user)) 
		{
		   	return array();
		}
		if (!is_numeric($limit)) 
		{
		   	$limit = 15;
		}
		
		$criteria= $this->paramHandler($criteria) . '%';
		
		//get gid
   		$sql = "SELECT gid
   				FROM groups
   				WHERE friendsgroup=$user";
   		$rez= $this->qry($sql,2);
   		
   		$gid=$rez['gid'];
  		
		$sql=" (SELECT g.gid as 'gid', g.name as 'name', rt.type as 'relation', g.visibility as 'visibility', g.description as 'description', g.friendsgroup as 'friendsgroup'
				 FROM groups g, relation_type rt
				 WHERE rt.gid=$gid
				  AND g.name like '$criteria'
				  AND g.friendsgroup=rt.uid
				  AND rt.type='M'
				)
				  union
				(
				  SELECT gid as 'gid', name as 'name', 'N' as 'relation', visibility as 'visibility', description as 'description', friendsgroup as 'friendsgroup'
				 FROM groups
				 WHERE gid not in (SELECT g.gid
				                     FROM groups g, relation_type rt
									 WHERE rt.gid=$gid
									  AND g.name like '$criteria'
									  AND g.friendsgroup=rt.uid
									  AND rt.type='M'
				                  )
				    AND visibility=1
				    AND name like '$criteria'
				    AND friendsgroup<>0 AND friendsgroup<>$user 
				)
				limit $limit;
		";
   		
   		$rez= $this->qry($sql,4);
   		$tmpCont = array();
   		
   		$ind = 0;
   		$row = mysql_fetch_assoc($rez);
   		while(null != $row)
   		{
   			$tmpCont[$ind]= Group::factorGroup($row);
   			$ind++;
   			$row = mysql_fetch_assoc($rez);
   		}
   		
   		return $tmpCont;
		
	} // end of function search group
	
	public function getUserFriends($user,$limit,$downpour,$relType)  
	{
		if (!is_numeric($user)) 
		{
		   	return array();
		}
		if (!is_numeric($limit)) 
		{
		   	$limit = 15;
		}
		if (!is_numeric($downpour)) 
		{
		   	$limit = 0;
		}
		if(!isset($relType) || sizeof($relType) != 1 )
			$relType = 'M';
			
		$relType = $this->paramHandler($relType);
		
		//get gid
   		$sql = "SELECT gid
   				FROM groups
   				WHERE friendsgroup=$user";
   		$rez= $this->qry($sql,2);
   		
   		$mygid=$rez['gid'];
		
		//select user's groups
		//add all visible groups without the intersection with previous group
		$sql="SELECT g.gid as 'gid', g.name as 'name', rt.type as 'relation', g.visibility as 'visibility', g.description as 'description',g.friendsgroup as 'friendsgroup'
				 FROM groups g, relation_type rt
				 WHERE rt.gid=$mygid
				  AND rt.uid=g.friendsgroup
				  AND g.gid > $downpour
				  AND rt.type = '$relType'		
				  ORDER BY g.gid
				limit $limit;
		";
   		
   		$rez= $this->qry($sql,4);
   		$tmpCont = array();
   		
   		$ind = 0;
   		$row = mysql_fetch_assoc($rez);
   		while(null != $row)
   		{
   			$tmpCont[$ind]= Group::factorGroup($row);
   			$ind++;
   			$row = mysql_fetch_assoc($rez);
   		}
   		
   		return $tmpCont;
		
	} // end of function get user friends
	
 	/** 
 	 * REGION_END user connections
 	 */
}

?>